package com.shuwei.wificollecttool;

import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.shuwei.location.wificollect.WifiCollectListener;
import com.shuwei.location.wificollect.WifiCollector;
import com.shuwei.location.wificollect.WifiItem;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Halohoop on 2017/11/23.
 */

public class SingleMainActivity extends AppCompatActivity implements WifiCollectListener<WifiItem>, View.OnClickListener {

    private WifiCollector wifiCollector;

    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;
    private Button btnCollect;
    private Button btnCollect2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_single);
        btnCollect = findViewById(R.id.btn_collect);
        btnCollect2 = findViewById(R.id.btn_collect2);
        btnCollect.setOnClickListener(this);
        btnCollect2.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerView);
        homeAdapter = new HomeAdapter(R.layout.item, new ArrayList());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(homeAdapter);

        //设置回调
//设置转换器,转换成自己需要的bean
//                .setSortTarget(WifiCollector.Config.SORT_TARGET_RSSI)//设置排序
//                .setSortType(WifiCollector.Config.SORT_TYPE_Z2A_9TO0_STRONGTOWEAK)//设置排序
//                .setCount(15)//设置需要前多少位
        wifiCollector = new WifiCollector.Builder<WifiItem>(this)
                .setWifiCollectListener(this)//设置回调
                .setConverter(new WifiCollector.Converter<WifiItem>() {
                    @Override
                    public WifiItem convert(ScanResult scanResult) {
                        WifiItem wifiItem = new WifiItem();
                        wifiItem.setBssid(scanResult.BSSID);
                        wifiItem.setRssi(scanResult.level);
                        wifiItem.setSsid(scanResult.SSID);
                        return wifiItem;
                    }
                })//设置转换器,转换成自己需要的bean
//                .setSortTarget(WifiCollector.Config.SORT_TARGET_RSSI)//设置排序
//                .setSortType(WifiCollector.Config.SORT_TYPE_Z2A_9TO0_STRONGTOWEAK)//设置排序
//                .setCount(15)//设置需要前多少位
                .create();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_collect:
                isNewFile = false;
                btnCollect.setEnabled(false);
                btnCollect2.setEnabled(false);
                wifiCollector.collect(null);
                break;
            case R.id.btn_collect2:
                writeCount = 0;
                isNewFile = true;
                btnCollect.setEnabled(false);
                btnCollect2.setEnabled(false);
                wifiCollector.collect(null);
                break;
            default:
                break;
        }
    }

    public class HomeAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public HomeAdapter(int layoutResId, List data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv_data, item);
        }
    }

    private File makeFile(File dir, boolean isAppend) {
        if (isAppend) {
            File[] files = dir.listFiles();
            if (files.length <= 0) {
                String txtFileName = System.currentTimeMillis() + ".xls";
                File file = new File(dir, txtFileName);
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file;
            } else if(files.length==1){
                return files[0];
            }
            File lastModifiedFile = files[0];
            for (int i = 0; i < files.length; i++) {
                if (i == 0) {
                    continue;
                }
                File file = files[i];
                if (lastModifiedFile.lastModified() < file.lastModified()) {
                    lastModifiedFile = file;
                }
            }
            return lastModifiedFile;
        } else {
            String txtFileName = System.currentTimeMillis() + ".xls";
            File file = new File(dir, txtFileName);
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }
    }

    private File makeDir() {
        File rootDir = Environment.getExternalStorageDirectory().getAbsoluteFile();
        File dir = new File(rootDir, "SW_WifiCollectTool");
        File dirSingle = new File(dir, "single");
        dirSingle.mkdirs();
        return dirSingle;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.single_main_menu, menu);
        return true;
    }

    public void onMenuClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_to_distribute:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    private int writeCount = 0;
    private boolean isNewFile = false;

    @Override
    public void wifiCollectSuccess(List<WifiItem> wifiItemList) {
        long l = System.currentTimeMillis();
        WifiSingleNeedHolder.getInstance().setWifiHolders(wifiItemList);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(l + "\r\n");
        Map<String, Object[]> rssiMap = new TreeMap<>();
        Object[] macs = new Object[wifiItemList.size()];
        Object[] rssis = new Object[wifiItemList.size()];
        Object[] ssids = new Object[wifiItemList.size()];
        for (int i = 0; i < wifiItemList.size(); i++) {
            WifiItem wifiItem = wifiItemList.get(i);
            if (App.DEBUG) {
                macs[i] =  "'" + wifiItem.getBssid() + "'";
                rssis[i] = macs[i] + ":" + wifiItem.getRssi();
                ssids[i] = macs[i] + ":" + wifiItem.getSsid();
            } else {
                macs[i] = "'" + wifiItem.getBssid() + "'";
                rssis[i] = wifiItem.getRssi();
                ssids[i] = wifiItem.getSsid();
            }
            stringBuffer.append(wifiItem.toString());
        }
        rssiMap.put(rssiMap.size() + "", macs);
        rssiMap.put(rssiMap.size() + "", rssis);
        rssiMap.put(rssiMap.size() + "", ssids);
        homeAdapter.addData(stringBuffer.toString());
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(homeAdapter.getItemCount() - 1);
            }
        });
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                btnCollect.setEnabled(true);
                btnCollect2.setEnabled(true);
            }
        }, 500);
        File dir = makeDir();
        File file = makeFile(dir, !isNewFile);
        try {
            SingleWriteSheet.writeMap(file, rssiMap, writeCount, isNewFile);
            writeCount++;
            writeCount++;
            writeCount++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void wifiCollectFail(int type, String msg) {
        switch (type) {
            case WifiCollector.TYPE_FAIL_WIFI_ERROR_OCCUR:
                showToast("TYPE_FAIL_WIFI_ERROR_OCCUR" + msg);
                break;
            case WifiCollector.TYPE_FAIL_WIFI_SWITCH_OFF:
                showToast("TYPE_FAIL_WIFI_SWITCH_OFF" + msg);
                break;
            default:
                break;
        }
    }

    private Toast toast;

    public void showToast(String s){
        if (toast==null) {
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.setText(s);
        toast.show();
    }
}
